package com.project.dao.Impl;

import com.project.bean.ChannelBane;
import com.project.dao.IChannelDao;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Repository
public class ChannelDaoImpl extends BaseDao implements IChannelDao {
    @Override
    public List<ChannelBane> findAll() {
        List<ChannelBane> list =new ArrayList<>();
            this.setConnection();
        try {
            ps=con.prepareStatement("SELECT c.*, COUNT(i.pk_inId)c FROM t_channel c JOIN t_invitation i ON c.pk_chId=i.fk_chId GROUP BY i.fk_chId");
            rs = ps.executeQuery();
            while (rs.next()){
             list.add(this.getChannel());
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }
        return list;
    }

    private ChannelBane getChannel()  {
        ChannelBane channelBane = new ChannelBane();
        try {
            channelBane.setId(rs.getInt("pk_chId"));
            channelBane.setName(rs.getString("c_name"));
            channelBane.setDescribe(rs.getString("c_describe"));
            channelBane.setThemeNum(rs.getInt("c"));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return channelBane;
    }

    @Override
    public ChannelBane findById(Integer id) {
        this.setConnection();
        try {
            ps=con.prepareStatement("SELECT c.*, COUNT(i.pk_inId)c FROM t_channel c JOIN t_invitation i ON c.pk_chId=i.fk_chId where c.pk_chId=? ");
            ps.setObject(1,id);
            rs=ps.executeQuery();
            if (rs.next()){
                return this.getChannel();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }
        return null;
    }
}
